<!-- /admin/messages.php -->
<?php
require_once(__DIR__ . '/../common/auth.php');
check_admin_login();
require_once(__DIR__ . '/../common/db.php');

// 状态映射
$status_map = [
    1 => '待审核',
    2 => '已通过',
    3 => '已回复',
    4 => '拒绝',
    0 => '已删除'
];

// 操作处理（全部使用预处理，防注入）
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? '';
    if (!$id) { $msg = "操作ID缺失"; }
    else {
        if (isset($_POST['approve'])) {
            $stmt = $db->prepare("UPDATE messages SET status=2 WHERE id=:id");
            $stmt->bindValue(':id', $id, SQLITE3_TEXT);
            $stmt->execute();
            $msg = "通过审核成功";
        }
        if (isset($_POST['reject'])) {
            $stmt = $db->prepare("UPDATE messages SET status=4 WHERE id=:id");
            $stmt->bindValue(':id', $id, SQLITE3_TEXT);
            $stmt->execute();
            $msg = "已拒绝";
        }
        if (isset($_POST['delete'])) {
            $stmt = $db->prepare("UPDATE messages SET status=0 WHERE id=:id");
            $stmt->bindValue(':id', $id, SQLITE3_TEXT);
            $stmt->execute();
            $msg = "已删除";
        }
        if (isset($_POST['reply'])) {
            $reply = trim($_POST['reply_content'] ?? '');
            $admin_name = $_SESSION['admin_name'] ?? '管理员';
            $new_status = $reply ? 3 : 2;
            $stmt = $db->prepare("UPDATE messages SET reply=:reply, reply_admin=:reply_admin, status=:status WHERE id=:id");
            $stmt->bindValue(':reply', $reply, SQLITE3_TEXT);
            $stmt->bindValue(':reply_admin', $admin_name, SQLITE3_TEXT);
            $stmt->bindValue(':status', $new_status, SQLITE3_INTEGER);
            $stmt->bindValue(':id', $id, SQLITE3_TEXT);
            $stmt->execute();
            $msg = "回复成功";
        }
    }
}

// 状态筛选
$filter = isset($_GET['status']) ? intval($_GET['status']) : -1;
$where = ($filter >= 0) ? "WHERE status=$filter" : "WHERE status>0";

// 分页参数
$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 10;
$offset = ($page - 1) * $pageSize;

// 总数与分页
$total = $db->querySingle("SELECT COUNT(*) FROM messages $where");
$pageCount = max(1, ceil($total / $pageSize));

// 读取分页留言
$res = $db->query("SELECT * FROM messages $where ORDER BY created_at DESC LIMIT $pageSize OFFSET $offset");
$messages = [];
while ($row = $res->fetchArray(SQLITE3_ASSOC)) $messages[] = $row;

// 姓名脱敏
function mask_name($name) {
    $len = mb_strlen($name, 'utf-8');
    if ($len == 2) return mb_substr($name, 0, 1, 'utf-8') . '*';
    if ($len == 3) return mb_substr($name, 0, 1, 'utf-8') . '*' . mb_substr($name, 2, 1, 'utf-8');
    if ($len > 3) return mb_substr($name, 0, 1, 'utf-8') . '*' . mb_substr($name, $len-1, 1, 'utf-8');
    return $name;
}
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>数据操作 - 工会留言板后台</title>
    <link rel="icon" href="/assets/logo.ico?v=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/assets/style.css?v=<?php echo time(); ?>">
    <style>
    .main { max-width: 900px !important; }
    .menu-tabs {
        display: flex; justify-content: flex-start; background: #f8fafb; border-radius: 14px; box-shadow: 0 2px 12px #f1f3f9;
        padding: 4px 12px; width: fit-content; margin: 0 auto 25px auto; border: 1.5px solid #e0e8f6;
    }
    .menu-tab { min-width: 96px; text-align: center; font-size: 1.08em; padding: 10px 0; border-radius: 8px;
        margin-right: 2px; color: #285bb7; background: transparent; border: none; outline: none; cursor: pointer;
        font-weight: 500; box-shadow: none; text-decoration: none; display: block; letter-spacing: 1px; user-select: none;
        transition: none;
    }
    .menu-tab.active { background: #e7f0ff; color: #1d388a; font-weight: bold; border: 1.5px solid #4576f5; box-shadow: 0 1px 4px #e3ebfa; }
    .menu-tab:hover { background: #e6eeff; color: #134378; border: 1.5px solid #b0cafe; }
    .menu-tab:last-child { margin-right: 0; }
    .msg-list-admin { display: flex; flex-direction: column; gap: 18px;}
    .msg-admin-item { background: #fff; border-radius: 14px; box-shadow: 0 2px 12px #e5eefd; padding: 22px 22px 14px 22px; margin-bottom: 0; position: relative;}
    .msg-admin-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 6px; }
    .msg-admin-name { font-weight: bold; color: #1d388a; font-size: 1.1em; }
    .msg-admin-dept, .msg-admin-contact, .msg-admin-date { color: #888; font-size: 0.98em; margin-right: 7px; }
    .msg-admin-content { color: #222; margin-bottom: 8px; font-size: 1.05em; word-break: break-all; }
    .msg-admin-reply-view { background: #f0f5ff; color: #2456a3; border-left: 3px solid #4576f5; border-radius: 4px; padding: 7px 13px; margin-bottom: 8px; }
    .msg-admin-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 3px; }
    .inline-form { display: inline-block; margin: 0 6px 0 0; }
    .reply-form-admin { display: flex; align-items: center; gap: 12px; width: 100%; margin-top: 6px; }
    .reply-box { width: 340px; min-height: 38px; border: 1px solid #bfcbe3; border-radius: 6px; padding: 6px 10px; font-size: 1em; resize: vertical; margin-right: 8px; background: #f9fbff; }
    .reply-box:focus { border: 1.5px solid #4576f5; background: #fff; outline: none; }
    .btn { display: inline-block; padding: 6px 20px; font-size: 1em; border: none; border-radius: 7px; background: #f5f8ff; color: #285bb7; cursor: pointer; box-shadow: 0 1px 2px #e3ebff; margin-right: 3px; vertical-align: middle; }
    .btn:hover { background: #d3e2ff; color: #12357a; }
    .btn.danger { background: #ffd8db; color: #ce3237; }
    .btn.danger:hover { background: #ffb5bb; color: #b12a2f; }
    .btn.green { background: #d1f2e6; color: #228868; }
    .btn.green:hover { background: #98e4ce; }
    .btn.blue { background: #cfe6ff; color: #225b99; }
    .btn.blue:hover { background: #b0d8ff; color: #134378; }
    .status-tag { display: inline-block; min-width: 48px; text-align: center; padding: 3px 13px; border-radius: 12px; font-size: 1em; font-weight: 500; white-space: nowrap; margin-right: 2px; margin-bottom: 0; line-height: 1.5; vertical-align: middle; }
    .status-1 {background: #f9ecb3; color: #b59100;}
    .status-2 {background: #d1f2e6; color: #228868;}
    .status-3 {background: #cfe6ff; color: #225b99;}
    .status-4 {background: #ffd8db; color: #ce3237;}
    .status-0 {background: #eee; color: #888;}
    .pagination-admin { margin: 32px 0 16px 0; text-align: center; }
    .pagination-btn, .pagination-btn-active {
        display: inline-block; min-width: 36px; height: 34px; line-height: 32px; margin: 0 3px; border-radius: 7px;
        font-size: 1em; border: none; background: #f2f6fd; color: #285bb7; text-align: center; text-decoration: none;
        font-weight: 500; cursor: pointer; user-select: none; outline: none; box-shadow: none; vertical-align: middle; transition: none;
    }
    .pagination-btn:hover { background: #e6eeff; color: #134378; }
    .pagination-btn-active { background: #4576f5; color: #fff; font-weight: bold; cursor: default; }
    @media (max-width: 900px) {
        .main { max-width: 98vw !important; padding: 8px 2vw; }
        .reply-box { width: 96vw; min-width: 60vw; }
        .msg-admin-meta { flex-wrap: wrap; gap: 7px;}
    }
    </style>
</head>
<body>
<?php include('../components/header.php'); ?>
<div style="display:flex;">
    <?php include('../components/menu.php'); ?>
    <div class="main" style="min-width:0;">
        <h2 class="msg-title">数据操作</h2>
        <!-- 菜单选项卡 -->
        <div class="menu-tabs">
            <a href="?status=-1" class="menu-tab <?php if($filter==-1)echo 'active'; ?>">全部</a>
            <a href="?status=1"  class="menu-tab <?php if($filter==1)echo 'active'; ?>">待审核</a>
            <a href="?status=2"  class="menu-tab <?php if($filter==2)echo 'active'; ?>">已通过</a>
            <a href="?status=3"  class="menu-tab <?php if($filter==3)echo 'active'; ?>">已回复</a>
            <a href="?status=4"  class="menu-tab <?php if($filter==4)echo 'active'; ?>">已拒绝</a>
        </div>
        <?php if($msg) echo "<div class='tip' style='margin-bottom:14px;'>".htmlspecialchars($msg)."</div>"; ?>

        <div class="msg-list-admin">
        <?php if (empty($messages)): ?>
            <div style="color:#888;text-align:center;padding:40px 0;">暂无留言</div>
        <?php else: foreach($messages as $m): ?>
            <div class="msg-admin-item">
                <div class="msg-admin-meta">
                    <span class="msg-admin-name"><?php echo htmlspecialchars(mask_name($m['name'])); ?></span>
                    <?php if ($m['department']) { ?>
                        <span class="msg-admin-dept"><?php echo htmlspecialchars($m['department']); ?></span>
                    <?php } ?>
                    <span class="msg-admin-contact"><?php echo htmlspecialchars($m['contact']); ?></span>
                    <span class="msg-admin-date"><?php echo date('Y-m-d H:i', strtotime($m['created_at'])); ?></span>
                    <span class="status-tag status-<?php echo $m['status']; ?>"><?php echo $status_map[$m['status']]; ?></span>
                </div>
                <div class="msg-admin-content">
                    <?php echo nl2br(htmlspecialchars($m['content'])); ?>
                </div>
                <?php if($m['reply']): ?>
                <div class="msg-admin-reply-view">
                    <?php
                        $admin_reply_name = !empty($m['reply_admin']) ? htmlspecialchars($m['reply_admin']) : '管理员';
                        echo $admin_reply_name . ' 回复：' . nl2br(htmlspecialchars($m['reply']));
                    ?>
                </div>
                <?php endif; ?>
                <div class="msg-admin-actions">
                    <?php if($m['status']==1): ?>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <button type="submit" name="approve" class="btn green">通过</button>
                        </form>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <button type="submit" name="reject" class="btn danger">拒绝</button>
                        </form>
                    <?php endif; ?>
                    <?php if($m['status']==2 || $m['status']==3): ?>
                        <form method="post" class="inline-form reply-form-admin">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <textarea name="reply_content" class="reply-box" placeholder="管理员回复"><?php echo htmlspecialchars($m['reply']??''); ?></textarea>
                            <button type="submit" name="reply" class="btn blue">提交回复</button>
                        </form>
                    <?php endif; ?>
                    <?php if($m['status']>0): ?>
                        <form method="post" class="inline-form">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <button type="submit" name="delete" class="btn" onclick="return confirm('确定删除？')">删除</button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; endif; ?>
        </div>

        <!-- 分页 -->
        <div class="pagination-admin">
            <?php if ($page > 1): ?>
                <a class="pagination-btn" href="?status=<?php echo $filter; ?>&page=1">&laquo;</a>
                <a class="pagination-btn" href="?status=<?php echo $filter; ?>&page=<?php echo $page-1; ?>">&lt;</a>
            <?php endif; ?>
            <?php
            $show = 5;
            $start = max(1, $page - 2);
            $end = min($pageCount, $start + $show - 1);
            if ($end - $start < $show - 1) $start = max(1, $end - $show + 1);
            for ($i = $start; $i <= $end; $i++) {
                if ($i == $page) {
                    echo '<span class="pagination-btn-active">'.$i.'</span>';
                } else {
                    echo '<a class="pagination-btn" href="?status='.$filter.'&page='.$i.'">'.$i.'</a>';
                }
            }
            ?>
            <?php if ($page < $pageCount): ?>
                <a class="pagination-btn" href="?status=<?php echo $filter; ?>&page=<?php echo $page+1; ?>">&gt;</a>
                <a class="pagination-btn" href="?status=<?php echo $filter; ?>&page=<?php echo $pageCount; ?>">&raquo;</a>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
